package com.bussiness;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.sql.SQLException;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.jws.WebService;

import com.beans.Movie;
import com.beans.Person;
import com.dao.PersonDAO;
import com.exceptions.DeleteCustomerWithOutstandingMovieException;
import com.exceptions.DeleteUserFailedException;
import com.exceptions.DuplicateUserIdException;
import com.exceptions.InvalidCustomerNameException;
import com.exceptions.InvalidEmailException;
import com.exceptions.InvalidUserNamePasswordException;
import com.exceptions.MinimumPwdLengthException;
import com.exceptions.MovieAlreadyDeletedException;
import com.exceptions.MovieAlreadyExistsException;
import com.exceptions.MovieUnavailableException;
import com.exceptions.PasswordNotMatchingException;
import com.exceptions.ServiceUnavailableException;
import com.exceptions.UserCartIsEmptyException;
import com.exceptions.UserException;
import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
import com.sun.org.apache.xml.internal.security.utils.Base64;
import com.validations.AllValidator;
import com.validations.Encrypt;

@WebService
public class PersonBussiness 
{
	public Person createUser(Person userData) throws DuplicateUserIdException,ServiceUnavailableException, InvalidEmailException, MinimumPwdLengthException, InvalidCustomerNameException, Exception
	{	
		Person status=new Person();
		boolean emailResult,firstnameResult,lastnameResult,passwordResult;
		emailResult = AllValidator.isEmailValid(userData.getEmailId());
		if(!emailResult)
		{
			throw new InvalidEmailException();
		}
		//Decode the password to check the validation of password.
	
		passwordResult=AllValidator.validate(Encrypt.decrypt(Base64.decode(userData.getPassword())));
		if(!passwordResult)
		{
			throw new MinimumPwdLengthException();
		}	
		firstnameResult = AllValidator.namevalidate(userData.getFirstName()) ;
		if(!firstnameResult)
		{
			throw new InvalidCustomerNameException();
		}	 
		lastnameResult = AllValidator.namevalidate(userData.getLastName());
		if(!lastnameResult)
		{
			throw new InvalidCustomerNameException();
		}
		else
		{
			System.out.println("In person business layer - createuser");
			PersonDAO persondao = new PersonDAO();	
				try
				{
					status=persondao.createUser(userData);	
				}
				catch(DuplicateUserIdException duplicate)
				{
					throw duplicate;
				}
				catch(ServiceUnavailableException serv)
				{
					throw serv;
				}
				catch(InvalidEmailException inve)
				{
					throw inve;
				}
				catch(MinimumPwdLengthException minpwd)
				{
					throw minpwd;
				}
				catch(InvalidCustomerNameException invcust)
				{
					throw invcust;
				}
				
		}			
		return status;
	}
	public Person validateUser(Person user) throws InvalidUserNamePasswordException,ServiceUnavailableException,PasswordNotMatchingException, InvalidCustomerNameException, InvalidEmailException, MinimumPwdLengthException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException, Exception
	{
		Person person=new Person();
		boolean emailResult,passwordResult;
		emailResult = AllValidator.isEmailValid(user.getEmailId());
		if(!emailResult)
		{
			throw new InvalidEmailException();
		}
		passwordResult=AllValidator.validate(Encrypt.decrypt(Base64.decode(user.getPassword())));
		if(!passwordResult)
		{
			throw new MinimumPwdLengthException();
		}	
		else
		{
			System.out.println("In person business layer - createuser");
			PersonDAO persondao = new PersonDAO();
			try
			{
			person=persondao.validateUser(user);
			}
			catch(InvalidUserNamePasswordException inv)
			{
				throw inv;	
			}
			catch(PasswordNotMatchingException pwdntmatch)
			{
				throw pwdntmatch;
			}
			catch(ServiceUnavailableException servunavl)
			{
				throw servunavl;	
			}
			catch(InvalidEmailException inve)
			{
				throw inve;
			}
			catch(MinimumPwdLengthException minpwd)
			{
				throw minpwd;
			}
		}
		return person;
	}
	
	public Person updateUser(Person userData) throws ServiceUnavailableException, InvalidEmailException, InvalidCustomerNameException, MinimumPwdLengthException,Exception
	{
		System.out.println("In person business layer - createuser");
		boolean firstnameResult,lastnameResult,passwordResult;
		//Decode the password to check the validation of password.
		passwordResult=AllValidator.validate(Encrypt.decrypt(Base64.decode(userData.getPassword())));
		if(!passwordResult)
		{
			throw new MinimumPwdLengthException();
		}	
		firstnameResult = AllValidator.namevalidate(userData.getFirstName()) ;
		if(!firstnameResult)
		{
			throw new InvalidCustomerNameException();
		}	 
		lastnameResult = AllValidator.namevalidate(userData.getLastName());
		if(!lastnameResult)
		{
			throw new InvalidCustomerNameException();
		}
		
		PersonDAO persondao = new PersonDAO();
		Person personData = null;
		try
		{
			personData=persondao.updateUser(userData);
		}
		catch(ServiceUnavailableException servunavl)
		{
			throw servunavl;
		}
		return personData;	
	}
	
	public int removeUser(String emailId) throws ServiceUnavailableException,DeleteCustomerWithOutstandingMovieException, UserException, InvalidEmailException, DeleteUserFailedException
	{	
		int status=0;
		System.out.println("In person business layer - createuser");
		PersonDAO persondao = new PersonDAO();
		
		boolean emailResult;
		emailResult = AllValidator.isEmailValid(emailId);
		if(!emailResult)
		{
			throw new InvalidEmailException();
		}
		try
		{
			status=persondao.removeUser(emailId);
		}
		catch(UserException user)
		{
			throw user;
		}
		catch(DeleteCustomerWithOutstandingMovieException delcust)
		{
			throw delcust;
		}
		catch(ServiceUnavailableException servunavl)
		{
			throw servunavl;
		}
		catch(InvalidEmailException inv)
		{
			throw inv;
		} 
		catch (DeleteUserFailedException e) 
		{
			throw e;
		}
		
		return status;	
	}
	public Movie[] customerorder(long memshipid) throws ServiceUnavailableException
	{
		Movie[] movie= null;
			System.out.println("In person business layer - customerorder");
			PersonDAO persondao = new PersonDAO();
			try
			{
			movie=persondao.customerorder(memshipid);
			}
			catch(ServiceUnavailableException servunavl)
			{
				throw servunavl;	
			}
		return movie;
	}
	public Movie[] customerqueue(long memshipid) throws ServiceUnavailableException,UserCartIsEmptyException
	{

		Movie[] movie= null;
			System.out.println("In person business layer - customerqueue");
			PersonDAO persondao = new PersonDAO();
			try
			{
			movie=persondao.customerqueue(memshipid);
			}
			catch(ServiceUnavailableException servunavl)
			{
				throw servunavl;	
			}
			catch(UserCartIsEmptyException empty)
			{
				throw empty;
			}
	
		return movie;
	}
	
	public byte[] encryptPassword(String plainText) throws InvalidKeyException, BadPaddingException,IllegalBlockSizeException, UnsupportedEncodingException
	{
		try
		{
			return Encrypt.encrypt(plainText);
		} 
		catch (InvalidKeyException e) 
		{
			throw e;
		} 
		catch (BadPaddingException e) 
		{
			throw e;
		} 
		catch (IllegalBlockSizeException e) 
		{
			throw e;
		}
	}
	public int addtoQueue(int movieid,long userid) throws MovieAlreadyExistsException,ServiceUnavailableException
	{
		int success=0;
			System.out.println("In person business layer - addtoQueue");
			PersonDAO persondao = new PersonDAO();
			try
			{
			success=persondao.addtoQueue(movieid,userid);
			}
			catch(ServiceUnavailableException servunavl)
			{
				throw servunavl;	
			}
			catch(MovieAlreadyExistsException empty)
			{
				throw empty;
			}	
		return success;	
	}
	public int removefromQueue(int movieid,long userid) throws ServiceUnavailableException,MovieAlreadyDeletedException
	{
		int success=0;
			System.out.println("In person business layer - removefromQueue");
			PersonDAO persondao = new PersonDAO();
			try
			{
			success=persondao.removefromQueue(movieid,userid);
			}
			catch(ServiceUnavailableException servunavl)
			{
				throw servunavl;	
			}
			catch(MovieAlreadyDeletedException movieunavl)
			{
				throw movieunavl;
			}
		
		return success;	
	}
	public String cardValidate(String card_number, int card_type){
		//String message;
		 switch(card_type) {
			
	        case 1:
	            if (card_number.length() != 16 ||
	                Integer.parseInt(card_number.substring(0, 2)) < 51 ||
	                Integer.parseInt(card_number.substring(0, 2)) > 55)
	            {
	                return "Invalid Credit Card Number.";
	            }
	            break;
				
	        case 2:
	            if ((card_number.length() != 16) || Integer.parseInt(card_number.substring(0, 1)) != 4)
	            {
	                return "Invalid Credit Card Number.";
	            }
	            break;
				
	        	            
		 }
		 return "success";
	}

	public Person[] getAllStates() throws ServiceUnavailableException
	{
		Person[] allStates = null;
		PersonDAO person=new PersonDAO();
		
		try
		{
			allStates=person.getAllStates();
		}
		catch(Exception e)
		{
			e.printStackTrace();
			System.out.println("\n Service is unavailable.");
			throw new ServiceUnavailableException();	
		
		}
		
		return allStates;
	}
}
